package com.pray.praymall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pray.common.enume.OrderStatusEnum;
import com.pray.common.to.SkuHasStockTo;
import com.pray.common.to.mq.OrderTo;
import com.pray.common.to.mq.StockDetailTo;
import com.pray.common.to.mq.StockLockedTo;
import com.pray.common.utils.PageUtils;
import com.pray.common.utils.Query;
import com.pray.common.utils.R;
import com.pray.praymall.ware.dao.WareSkuDao;
import com.pray.praymall.ware.entity.WareOrderTaskDetailEntity;
import com.pray.praymall.ware.entity.WareOrderTaskEntity;
import com.pray.praymall.ware.entity.WareSkuEntity;
import com.pray.praymall.ware.exception.NoStockException;
import com.pray.praymall.ware.feign.OrderFeignService;
import com.pray.praymall.ware.feign.ProductFeignService;
import com.pray.praymall.ware.service.WareOrderTaskDetailService;
import com.pray.praymall.ware.service.WareOrderTaskService;
import com.pray.praymall.ware.service.WareSkuService;
import com.pray.praymall.ware.vo.OrderItemVo;
import com.pray.praymall.ware.vo.OrderVo;
import com.pray.praymall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private WareSkuDao wareSkuDao;

    @Resource
    private ProductFeignService feignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService taskService;

    @Autowired
    private WareOrderTaskDetailService taskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;


    // /**
    //  * 库存自动解锁
    //  *
    //  * @param to
    //  * @param message
    //  */
    // @RabbitHandler
    // public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
    //     log.info("收到解锁库存的消息");
    //     StockDetailTo detail = to.getDetail();
    //     // 解锁
    //     // 1、查询数据库关于这个订单的锁定库存信息
    //     // 如果有：证明库存锁定成功了
    //     // 解锁：看订单情况
    //     //      1、没有这个订单，必须解锁
    //     //      2、有这个订单，要继续看订单状态
    //     //          已取消：解锁库存
    //     //          没取消：不能解锁
    //     // 如果没有：说明库存锁定失败，库存回滚了，这种情况无需解锁
    //     WareOrderTaskDetailEntity detailEntity = taskDetailService.getById(detail.getId());
    //     if (detailEntity != null) {
    //         // 解锁库存
    //         WareOrderTaskEntity taskEntity = taskService.getById(to.getId());
    //         // 根据订单号查询订单状态
    //         R r = orderFeignService.getOrderStatus(taskEntity.getOrderSn());
    //         if (r.getCode() == 0) {
    //             OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
    //             });
    //             if (orderVo == null || OrderStatusEnum.CANCLED.getCode().equals(orderVo.getStatus())) {
    //                 // 订单不存在或者订单是已取消的状态，需要进行库存解锁
    //                 unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getId());
    //                 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    //             }
    //         } else {
    //             // 消息拒绝后重新放到队列，让别人继续消费解锁
    //             channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
    //         }
    //     } else {
    //         channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    //     }
    // }

    /**
     * 解锁库存
     *
     * @param skuId        商品id
     * @param wareId       仓库id
     * @param num          需要解锁的数量
     * @param taskDetailId 工作单详情id
     */
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unLockStock(skuId, wareId, num);
        // 更新库存工作单详情的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        // 变为已解锁
        detailEntity.setLockStatus(2);
        taskDetailService.updateById(detailEntity);
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 1.如果还没有这个库存记录，就进行新增
        Integer count = wareSkuDao.selectCount(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (count == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            // TODO 远程查询sku的名字
            try {
                R r = feignService.info(skuId);
                if (r.getCode() == 0) {
                    Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                    skuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            } catch (Exception e) {
                log.error("**********远程服务查询商品名称失败：" + e);
            }

            wareSkuDao.insert(skuEntity);
        }
        wareSkuDao.addStock(skuId, wareId, skuNum);
    }

    @Override
    public List<SkuHasStockTo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> stock = skuIds.stream().map(skuId -> {
            SkuHasStockTo stockVo = new SkuHasStockTo();
            // 查询当前sku的库存量
            Long count = this.baseMapper.getSkuStock(skuId);
            stockVo.setSkuId(skuId);
            stockVo.setHasStock(count != null && count > 0);
            return stockVo;
        }).collect(Collectors.toList());
        return stock;
    }

    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        // 保存库存工作单的详情，追溯
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        taskService.save(taskEntity);


        // 1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareIds(wareIds);
            return stock;
        }).collect(Collectors.toList());

        // 2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareIds();
            if (wareIds == null || wareIds.size() == 0) {
                // 没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                // 返回0说明失败
                Integer count = baseMapper.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count != 0) {
                    skuStocked = true;
                    // 当前仓库锁成功
                    // 需要给MQ发送消息
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null,
                            skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    taskDetailService.save(taskDetailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }
            }

            if (!skuStocked) {
                // 当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        // log.info("收到解锁库存的消息");
        StockDetailTo detail = to.getDetail();
        // 解锁
        // 1、查询数据库关于这个订单的锁定库存信息
        // 如果有：证明库存锁定成功了
        // 解锁：看订单情况
        //      1、没有这个订单，必须解锁
        //      2、有这个订单，要继续看订单状态
        //          已取消：解锁库存
        //          没取消：不能解锁
        // 如果没有：说明库存锁定失败，库存回滚了，这种情况无需解锁
        WareOrderTaskDetailEntity detailEntity = taskDetailService.getById(detail.getId());
        if (detailEntity != null) {
            // 解锁库存
            WareOrderTaskEntity taskEntity = taskService.getById(to.getId());
            // 根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(taskEntity.getOrderSn());
            if (r.getCode() == 0) {
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                if (orderVo == null || OrderStatusEnum.CANCLED.getCode().equals(orderVo.getStatus())) {
                    // 订单不存在或者订单是已取消的状态，需要进行库存解锁
                    if (detailEntity.getLockStatus() == 1) {
                        // 库存工作单是已锁定的才可以进行解锁
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getId());
                    }
                }
            } else {
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期，查订单状态是新建状态，什么都不做就结束了
     * 导致卡顿的订单，永远都不能解锁库存
     *
     * @param to
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        // 查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity taskEntity = taskService.getOrderTaskByOrderSn(to.getOrderSn());
        Long taskId = taskEntity.getId();
        // 按照库存工作单id查询所有未被解锁的库存工作单详情进行解锁
        List<WareOrderTaskDetailEntity> entities = taskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", taskId)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    @Data
    class SkuWareHasStock {
        /**
         * 商品id
         */
        private Long skuId;
        /**
         * 仓库id
         */
        private List<Long> wareIds;
        /**
         * 需要锁定的数量
         */
        private Integer num;
    }

}